import { ref, onBeforeMount, onBeforeUnmount, watch, useSlots, computed, openBlock, createElementBlock, normalizeStyle, toDisplayString, createCommentVNode, createElementVNode, createVNode, Fragment, renderList, normalizeClass, createBlock, withCtx, unref, isRef, renderSlot, createTextVNode, onMounted, onUpdated, onUnmounted, normalizeProps, mergeProps, nextTick, guardReactiveProps, toRaw, createSlots } from "vue";
import { I as Input, _ as __unplugin_components_1, L as LayoutSider, a as LayoutContent, b as __unplugin_components_2, c as __unplugin_components_1$1, A as Avatar, d as __unplugin_components_2$1, e as __unplugin_components_0, B as Button, M as Modal, f as __unplugin_components_2$2, S as Spin } from "./ant-design-vue.js";
import { h as html2canvas } from "./html2canvas.js";
import { message } from "ant-design-vue";
import { c as copyToClipboard } from "./copy-to-clipboard.js";
import { m as markdownIt } from "./markdown-it.js";
import { m as markdownItLinkAttributes } from "./markdown-it-link-attributes.js";
import { H as HighlightJS } from "./highlight.js.js";
import { p as pdf, a as pdf_viewer } from "./pdfjs-dist.js";
import { f as ExclamationCircleOutlined } from "./@ant-design.js";
import { f as fetchEventSource } from "./@microsoft.js";
import { l as localforage } from "./localforage.js";
import "./@babel.js";
import "./resize-observer-polyfill.js";
import "./lodash-es.js";
import "./vue-types.js";
import "./dom-align.js";
import "./@ctrl.js";
import "./toggle-selection.js";
import "./entities.js";
import "./uc.micro.js";
import "./mdurl.js";
import "./linkify-it.js";
function useMediaQuery(query, options = {}) {
  const { win = window } = options;
  const isSupported = Boolean(win && "matchMedia" in win && typeof win.matchMedia === "function");
  let mediaQuery;
  const matches = ref(false);
  const update = () => {
    if (!isSupported)
      return;
    if (!mediaQuery) {
      mediaQuery = window.matchMedia(query);
    }
    matches.value = mediaQuery.matches;
  };
  onBeforeMount(() => {
    update();
    if (!mediaQuery)
      return;
    if ("addEventListener" in mediaQuery) {
      mediaQuery.addEventListener("change", update);
    } else {
      mediaQuery.addListener(update);
    }
    onBeforeUnmount(() => {
      if ("removeEventListener" in mediaQuery) {
        mediaQuery.removeEventListener("change", update);
      } else {
        mediaQuery.removeListener(update);
      }
    });
  });
  return matches;
}
function useMobile() {
  return useMediaQuery("(max-width: 760px)");
}
function useCollapsed() {
  const key = "CHATAICOLLAPSED";
  const isMobile = useMobile();
  function getCurCollapsed() {
    const local = JSON.parse(localStorage.getItem(key) || "{}");
    return isMobile.value ? true : local.collapsed || false;
  }
  const collapsed = ref(getCurCollapsed());
  watch(isMobile, () => {
    collapsed.value = getCurCollapsed();
  });
  function get() {
    return collapsed.value;
  }
  function set(value) {
    collapsed.value = value;
    localStorage.setItem(key, JSON.stringify({ collapsed: value }));
  }
  function toggle() {
    set(!collapsed.value);
  }
  return {
    get,
    set,
    toggle,
    collapsed
  };
}
var svgData = {
  delete: {
    body: '<path fill="currentColor" d="M17 6h5v2h-2v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V8H2V6h5V3a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v3Zm1 2H6v12h12V8Zm-9 3h2v6H9v-6Zm4 0h2v6h-2v-6ZM9 4v2h6V4H9Z"/>'
  },
  "stop-response": {
    body: '<path fill="currentColor" d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10s-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16a8 8 0 0 0 0 16ZM9 9h6v6H9V9Z"/>'
  },
  "hello-msg": {
    body: '<path fill="currentColor" d="M16 16a3 3 0 1 1 0 6a3 3 0 0 1 0-6ZM6 12a4 4 0 1 1 0 8a4 4 0 0 1 0-8Zm8.5-10a5.5 5.5 0 1 1 0 11a5.5 5.5 0 0 1 0-11Z"/>'
  },
  download: {
    body: '<path fill="currentColor" d="M13 10h5l-6 6l-6-6h5V3h2v7Zm-9 9h16v-7h2v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-8h2v7Z"/>'
  },
  send: {
    body: '<path fill="currentColor" d="M1.946 9.316c-.522-.175-.526-.456.011-.635L21.043 2.32c.529-.176.832.12.684.638l-5.453 19.086c-.151.529-.456.547-.68.045L12 14l6-8l-8 6l-8.054-2.684Z"/>'
  },
  chat: {
    body: '<path d="M29.71,13.09A8.09,8.09,0,0,0,20.34,2.68a8.08,8.08,0,0,0-13.7,2.9A8.08,8.08,0,0,0,2.3,18.9,8,8,0,0,0,3,25.45a8.08,8.08,0,0,0,8.69,3.87,8,8,0,0,0,6,2.68,8.09,8.09,0,0,0,7.7-5.61,8,8,0,0,0,5.33-3.86A8.09,8.09,0,0,0,29.71,13.09Zm-12,16.82a6,6,0,0,1-3.84-1.39l.19-.11,6.37-3.68a1,1,0,0,0,.53-.91v-9l2.69,1.56a.08.08,0,0,1,.05.07v7.44A6,6,0,0,1,17.68,29.91ZM4.8,24.41a6,6,0,0,1-.71-4l.19.11,6.37,3.68a1,1,0,0,0,1,0l7.79-4.49V22.8a.09.09,0,0,1,0,.08L13,26.6A6,6,0,0,1,4.8,24.41ZM3.12,10.53A6,6,0,0,1,6.28,7.9v7.57a1,1,0,0,0,.51.9l7.75,4.47L11.85,22.4a.14.14,0,0,1-.09,0L5.32,18.68a6,6,0,0,1-2.2-8.18Zm22.13,5.14-7.78-4.52L20.16,9.6a.08.08,0,0,1,.09,0l6.44,3.72a6,6,0,0,1-.9,10.81V16.56A1.06,1.06,0,0,0,25.25,15.67Zm2.68-4-.19-.12-6.36-3.7a1,1,0,0,0-1.05,0l-7.78,4.49V9.2a.09.09,0,0,1,0-.09L19,5.4a6,6,0,0,1,8.91,6.21ZM11.08,17.15,8.38,15.6a.14.14,0,0,1-.05-.08V8.1a6,6,0,0,1,9.84-4.61L18,3.6,11.61,7.28a1,1,0,0,0-.53.91ZM12.54,14,16,12l3.47,2v4L16,20l-3.47-2Z" fill="currentColor" />'
  },
  more: {
    body: '<path fill="currentColor" d="M12 3c-1.1 0-2 .9-2 2s.9 2 2 2s2-.9 2-2s-.9-2-2-2Zm0 14c-1.1 0-2 .9-2 2s.9 2 2 2s2-.9 2-2s-.9-2-2-2Zm0-7c-1.1 0-2 .9-2 2s.9 2 2 2s2-.9 2-2s-.9-2-2-2Z"/>'
  },
  refresh: {
    body: '<path fill="currentColor" d="M18.537 19.567A9.961 9.961 0 0 1 12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10c0 2.136-.67 4.116-1.81 5.74L17 12h3a8 8 0 1 0-2.46 5.772l.997 1.795Z"/>'
  },
  copy: {
    body: '<path fill="currentColor" d="M7 6V3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1h-3v3c0 .552-.45 1-1.007 1H4.007A1.001 1.001 0 0 1 3 21l.003-14c0-.552.45-1 1.006-1H7ZM5.002 8L5 20h10V8H5.002ZM9 6h8v10h2V4H9v2Zm-2 5h6v2H7v-2Zm0 4h6v2H7v-2Z"/>'
  },
  empty: {
    body: '<path fill="currentColor" d="M21 3a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h18ZM7.416 14H4v5h16v-5h-3.416a5.001 5.001 0 0 1-9.168 0ZM20 5H4v7h5a3 3 0 1 0 6 0h5V5Z"/>'
  },
  msg: {
    body: '<path fill="currentColor" d="M2 8.994A5.99 5.99 0 0 1 8 3h8c3.313 0 6 2.695 6 5.994V21H8c-3.313 0-6-2.695-6-5.994V8.994ZM20 19V8.994A4.004 4.004 0 0 0 16 5H8a3.99 3.99 0 0 0-4 3.994v6.012A4.004 4.004 0 0 0 8 19h12Zm-6-8h2v2h-2v-2Zm-6 0h2v2H8v-2Z"/>'
  },
  edit: {
    body: '<path fill="currentColor" d="M6.414 15.89L16.556 5.748l-1.414-1.414L5 14.476v1.414h1.414Zm.829 2H3v-4.243L14.435 2.212a1 1 0 0 1 1.414 0l2.829 2.829a1 1 0 0 1 0 1.414L7.243 17.89ZM3 19.89h18v2H3v-2Z"/>'
  },
  save: {
    body: '<path fill="currentColor" d="M7 19v-6h10v6h2V7.828L16.172 5H5v14h2ZM4 3h13l4 4v13a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm5 12v4h6v-4H9Z"/>'
  },
  arrow: {
    body: `<path d="M5.64645 3.14645C5.45118 3.34171 5.45118 3.65829 5.64645 3.85355L9.79289 8L5.64645 12.1464C5.45118 12.3417 5.45118 12.6583 5.64645 12.8536C5.84171 13.0488 6.15829 13.0488 6.35355 12.8536L10.8536 8.35355C11.0488 8.15829 11.0488 7.84171 10.8536 7.64645L6.35355 3.14645C6.15829 2.95118 5.84171 2.95118 5.64645 3.14645Z" fill="currentColor"></path>`
  },
  file: {
    body: `<path d="M842.666667 285.866667l-187.733334-187.733334c-14.933333-14.933333-32-21.333333-53.333333-21.333333H234.666667C194.133333 74.666667 160 108.8 160 149.333333v725.333334c0 40.533333 34.133333 74.666667 74.666667 74.666666h554.666666c40.533333 0 74.666667-34.133333 74.666667-74.666666V337.066667c0-19.2-8.533333-38.4-21.333333-51.2z m-44.8 44.8c-2.133333 2.133333-4.266667 0-8.533334 0h-170.666666c-6.4 0-10.666667-4.266667-10.666667-10.666667V149.333333c0-2.133333 0-6.4-2.133333-8.533333 0 0 2.133333 0 2.133333 2.133333l189.866667 187.733334z m-8.533334 554.666666H234.666667c-6.4 0-10.666667-4.266667-10.666667-10.666666V149.333333c0-6.4 4.266667-10.666667 10.666667-10.666666h311.466666c-2.133333 4.266667-2.133333 6.4-2.133333 10.666666v170.666667c0 40.533333 34.133333 74.666667 74.666667 74.666667h170.666666c4.266667 0 6.4 0 10.666667-2.133334V874.666667c0 6.4-4.266667 10.666667-10.666667 10.666666z" fill="#666666" p-id="3611"></path><path d="M640 693.333333H341.333333c-17.066667 0-32 14.933333-32 32s14.933333 32 32 32h298.666667c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32zM640 522.666667H341.333333c-17.066667 0-32 14.933333-32 32s14.933333 32 32 32h298.666667c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32zM341.333333 416h85.333334c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32h-85.333334c-17.066667 0-32 14.933333-32 32s14.933333 32 32 32z" fill="currentColor" p-id="3612"></path>`
  }
};
var index_vue_vue_type_style_index_0_scoped_true_lang = "";
var _export_sfc = (sfc, props) => {
  const target = sfc.__vccOpts || sfc;
  for (const [key, val] of props) {
    target[key] = val;
  }
  return target;
};
const _hoisted_1$7 = ["width", "height", "viewBox", "aria-labelledby"];
const _hoisted_2$7 = ["id"];
const _hoisted_3$6 = ["innerHTML"];
const _sfc_main$b = {
  __name: "index",
  props: {
    placeholder: {
      type: String,
      default: ""
    },
    type: {
      type: String,
      default: "icon"
    },
    color: {
      type: String,
      default: "currentColor"
    },
    width: {
      type: [Number, String],
      default: 0
    },
    height: {
      type: [Number, String],
      default: 0
    },
    size: {
      type: [Number, String],
      default: 16
    },
    viewBox: {
      type: String,
      default: "0 0 24 24"
    }
  },
  setup(__props) {
    useSlots();
    const props = __props;
    const content = computed(() => {
      if (svgData[props.type]) {
        return svgData[props.type].body;
      }
      return "";
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("svg", {
        xmlns: "http://www.w3.org/2000/svg",
        width: parseFloat(__props.width || __props.size),
        height: parseFloat(__props.height || __props.size),
        viewBox: __props.viewBox,
        "aria-labelledby": __props.type,
        role: "presentation",
        style: normalizeStyle({ color: __props.color }),
        class: "icon-svg"
      }, [
        __props.placeholder ? (openBlock(), createElementBlock("title", {
          key: 0,
          id: __props.type,
          lang: "en"
        }, toDisplayString(__props.placeholder), 9, _hoisted_2$7)) : createCommentVNode("", true),
        createElementVNode("g", {
          fill: "none",
          innerHTML: content.value
        }, null, 8, _hoisted_3$6)
      ], 12, _hoisted_1$7);
    };
  }
};
var IconSvg = /* @__PURE__ */ _export_sfc(_sfc_main$b, [["__scopeId", "data-v-7190fd02"]]);
var list_vue_vue_type_style_index_0_lang = "";
const _hoisted_1$6 = { class: "chatai-list-wrapper" };
const _hoisted_2$6 = {
  key: 0,
  class: "chatai-empty"
};
const _hoisted_3$5 = /* @__PURE__ */ createElementVNode("span", { class: "chatai-emptxt" }, "\u6682\u65E0\u8BB0\u5F55", -1);
const _hoisted_4$4 = ["onClick"];
const _hoisted_5$4 = { class: "chatai-record-txt" };
const _hoisted_6$2 = { key: 1 };
const _hoisted_7$2 = {
  key: 0,
  class: "chatai-record-active"
};
const _sfc_main$a = {
  __name: "list",
  props: {
    chatStore: {
      type: Object,
      default: () => ({})
    }
  },
  setup(__props) {
    const props = __props;
    const { chatStateRef, setActive, updateRecord, deleteRecord } = props.chatStore;
    const dataSources = computed(() => chatStateRef.value.record);
    function isActive(uuid) {
      return chatStateRef.value.active === uuid;
    }
    async function handleSelect({ uuid }) {
      if (isActive(uuid)) {
        return;
      }
      if (chatStateRef.value.active) {
        updateRecord(chatStateRef.value.active, { isEdit: false });
      }
      await setActive(uuid);
    }
    function handleEdit({ uuid }, isEdit, event) {
      event == null ? void 0 : event.stopPropagation();
      updateRecord(uuid, { isEdit });
    }
    function handleDelete(index, event) {
      event == null ? void 0 : event.stopPropagation();
      deleteRecord(index);
    }
    function handleEnter({ uuid }, isEdit, event) {
      event == null ? void 0 : event.stopPropagation();
      if (event.key === "Enter") {
        updateRecord(uuid, { isEdit });
      }
    }
    return (_ctx, _cache) => {
      const _component_a_input = Input;
      const _component_a_popconfirm = __unplugin_components_1;
      return openBlock(), createElementBlock("div", _hoisted_1$6, [
        !dataSources.value.length ? (openBlock(), createElementBlock("div", _hoisted_2$6, [
          createVNode(IconSvg, {
            type: "empty",
            size: "30"
          }),
          _hoisted_3$5
        ])) : (openBlock(true), createElementBlock(Fragment, { key: 1 }, renderList(dataSources.value, (item, index) => {
          return openBlock(), createElementBlock("div", {
            key: index,
            class: normalizeClass(["chatai-record-box", isActive(item.uuid) ? "active" : ""]),
            onClick: ($event) => handleSelect(item)
          }, [
            createVNode(IconSvg, { type: "msg" }),
            createElementVNode("div", _hoisted_5$4, [
              item.isEdit ? (openBlock(), createBlock(_component_a_input, {
                key: 0,
                value: item.title,
                "onUpdate:value": ($event) => item.title = $event,
                size: "small",
                onKeypress: ($event) => handleEnter(item, false, $event)
              }, null, 8, ["value", "onUpdate:value", "onKeypress"])) : (openBlock(), createElementBlock("span", _hoisted_6$2, toDisplayString(item.title), 1))
            ]),
            isActive(item.uuid) ? (openBlock(), createElementBlock("div", _hoisted_7$2, [
              item.isEdit ? (openBlock(), createBlock(IconSvg, {
                key: 0,
                type: "save",
                onClick: ($event) => handleEdit(item, false, $event),
                style: { "margin-left": "4px", "margin-right": "0" }
              }, null, 8, ["onClick"])) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                createVNode(IconSvg, {
                  type: "edit",
                  onClick: ($event) => handleEdit(item, true, $event),
                  style: { "margin-left": "4px" }
                }, null, 8, ["onClick"]),
                createVNode(_component_a_popconfirm, {
                  placement: "bottom",
                  onConfirm: ($event) => handleDelete(index, $event),
                  title: "\u786E\u5B9A\u5220\u9664\u6B64\u8BB0\u5F55?",
                  okText: "\u786E\u5B9A",
                  cancelText: "\u53D6\u6D88"
                }, {
                  default: withCtx(() => [
                    createVNode(IconSvg, {
                      type: "delete",
                      style: { "margin-right": "0" }
                    })
                  ]),
                  _: 2
                }, 1032, ["onConfirm"])
              ], 64))
            ])) : createCommentVNode("", true)
          ], 10, _hoisted_4$4);
        }), 128))
      ]);
    };
  }
};
var index_vue_vue_type_style_index_0_lang$3 = "";
const _sfc_main$9 = {
  __name: "index",
  props: {
    sideWidth: {
      type: [String, Number],
      default: 260
    },
    chatStore: {
      type: Object,
      default: () => ({})
    }
  },
  setup(__props) {
    const props = __props;
    const { collapsed, toggle } = useCollapsed();
    const { addRecord } = props.chatStore;
    function handleCreate() {
      addRecord({ title: "\u65B0\u7684\u804A\u5929", uuid: Date.now(), isEdit: false });
    }
    function handleCollapsed() {
      toggle();
    }
    return (_ctx, _cache) => {
      const _component_a_layout_sider = LayoutSider;
      const _component_a_layout_content = LayoutContent;
      const _component_a_layout = __unplugin_components_2;
      return openBlock(), createBlock(_component_a_layout, { class: "chatai-layout-wrapper" }, {
        default: withCtx(() => [
          createVNode(_component_a_layout_sider, {
            collapsed: unref(collapsed),
            "onUpdate:collapsed": _cache[0] || (_cache[0] = ($event) => isRef(collapsed) ? collapsed.value = $event : null),
            trigger: null,
            collapsible: "",
            class: normalizeClass(["chatai-layout-sider", unref(collapsed) ? "shrink" : ""]),
            width: props.sideWidth,
            theme: "light",
            collapsedWidth: 0
          }, {
            default: withCtx(() => [
              createElementVNode("div", {
                class: "chatai-create-btn",
                onClick: handleCreate
              }, "\u65B0\u5EFA\u804A\u5929"),
              createVNode(_sfc_main$a, { chatStore: __props.chatStore }, null, 8, ["chatStore"]),
              createElementVNode("div", {
                class: "chatai-collapse",
                onClick: handleCollapsed
              }, [
                createVNode(IconSvg, {
                  type: "arrow",
                  size: "18",
                  viewBox: "0 0 16 16",
                  class: normalizeClass([!unref(collapsed) ? "reverse" : ""])
                }, null, 8, ["class"])
              ])
            ]),
            _: 1
          }, 8, ["collapsed", "class", "width"]),
          createVNode(_component_a_layout_content, { class: "chatai-layout-content" }, {
            default: withCtx(() => [
              renderSlot(_ctx.$slots, "default")
            ]),
            _: 3
          })
        ]),
        _: 3
      });
    };
  }
};
let scrollContainer = null;
function setScrollNode(node) {
  scrollContainer = node;
}
function getScrollNode() {
  return scrollContainer;
}
function getElementLeft(element) {
  var actualLeft = element.offsetLeft;
  var current = element.offsetParent;
  while (current !== null) {
    actualLeft += current.offsetLeft;
    current = current.offsetParent;
  }
  return actualLeft;
}
function getElementTop(element) {
  var actualTop = element.offsetTop;
  var current = element.offsetParent;
  while (current !== null) {
    actualTop += current.offsetTop;
    current = current.offsetParent;
  }
  return actualTop;
}
async function exportToImage(el, watermarkConfig = {}) {
  try {
    const canvas = await html2canvas(el, {
      useCORS: true
    });
    await addWatermark(el, canvas, watermarkConfig);
    const imgUrl = canvas.toDataURL("image/png");
    const tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = imgUrl;
    tempLink.setAttribute("download", "chat-msg.png");
    if (typeof tempLink.download === "undefined") {
      tempLink.setAttribute("target", "_blank");
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    window.URL.revokeObjectURL(imgUrl);
    Promise.resolve();
  } catch (err) {
    console.log("exportToImage err: ", exportToImage);
    return Promise.reject(err);
  }
}
function addWatermark(el, canvas, config2) {
  if (!config2.text)
    return;
  return new Promise((resolve) => {
    setTimeout(() => {
      const ctx = canvas.getContext("2d");
      const width = Math.max(el.offsetWidth, el.clientWidth);
      const height = Math.max(el.offsetHeight, el.clientHeight);
      const offsetX = getElementLeft(el);
      const offsetY = -(-getElementTop(el) + el.parentNode.scrollTop);
      const { text, font, color, spaceX, spaceY, angle } = config2;
      ctx.translate(offsetX, offsetY);
      ctx.font = font;
      ctx.fillStyle = color;
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      const maxWidth = width + spaceX;
      const maxHeight = height + spaceY + 300;
      for (let x = 0; x < maxWidth; x += spaceX) {
        for (let y = 0; y <= maxHeight; y += spaceY) {
          ctx.save();
          ctx.translate(x, y);
          ctx.rotate(angle);
          ctx.fillText(text, 0, 0);
          ctx.restore();
        }
      }
      resolve();
    });
  });
}
function getPopupContainer(node) {
  const scrollNode = getScrollNode();
  if (scrollNode) {
    return scrollNode;
  }
  getPopupContainer2(node);
}
function getPopupContainer2(node) {
  if (node) {
    return node.parentNode;
  }
  return document.body;
}
function debounce(fn, delay) {
  let timeout = null;
  return function(...rest) {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      fn.apply(this, rest);
      timeout = null;
    }, delay);
  };
}
function simpleDeepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}
var button_vue_vue_type_style_index_0_lang = "";
const _sfc_main$8 = {
  __name: "button",
  emits: ["click"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    function handleClick() {
      emit("click");
    }
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("button", {
        class: "chatai-hover-btn",
        onClick: handleClick
      }, [
        renderSlot(_ctx.$slots, "default")
      ]);
    };
  }
};
const _hoisted_1$5 = { key: 0 };
const _hoisted_2$5 = { key: 1 };
const _sfc_main$7 = {
  __name: "index",
  props: {
    tooltip: {
      type: String,
      default: ""
    },
    placement: {
      type: String,
      default: "top"
    }
  },
  emits: ["click"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const isMobile = useMobile();
    const showTooltip = computed(() => Boolean(props.tooltip) && !isMobile);
    function handleClick() {
      emit("click");
    }
    return (_ctx, _cache) => {
      const _component_a_tooltip = __unplugin_components_1$1;
      return showTooltip.value ? (openBlock(), createElementBlock("div", _hoisted_1$5, [
        createVNode(_component_a_tooltip, {
          placement: __props.placement,
          trigger: "hover",
          getPopupContainer: unref(getPopupContainer2)
        }, {
          title: withCtx(() => [
            createTextVNode(toDisplayString(__props.tooltip), 1)
          ]),
          default: withCtx(() => [
            createVNode(_sfc_main$8, { onClick: handleClick }, {
              default: withCtx(() => [
                renderSlot(_ctx.$slots, "default")
              ]),
              _: 3
            })
          ]),
          _: 3
        }, 8, ["placement", "getPopupContainer"])
      ])) : (openBlock(), createElementBlock("div", _hoisted_2$5, [
        createVNode(_sfc_main$8, { onClick: handleClick }, {
          default: withCtx(() => [
            renderSlot(_ctx.$slots, "default")
          ]),
          _: 3
        })
      ]));
    };
  }
};
var highlight = "";
var githubMarkdown = "";
var text_vue_vue_type_style_index_0_lang = "";
const _hoisted_1$4 = { key: 0 };
const _hoisted_2$4 = ["innerHTML"];
const _hoisted_3$4 = ["textContent"];
const _hoisted_4$3 = ["textContent"];
const _hoisted_5$3 = {
  key: 2,
  class: "chatai-animate-blink"
};
const _sfc_main$6 = {
  __name: "text",
  props: {
    inversion: {
      type: Boolean,
      default: false
    },
    error: {
      type: Boolean,
      default: false
    },
    text: {
      type: String,
      default: ""
    },
    loading: {
      type: Boolean,
      default: false
    },
    asRawText: {
      type: Boolean,
      default: false
    }
  },
  setup(__props) {
    const props = __props;
    const textRef = ref();
    const mdi = new markdownIt({
      html: true,
      linkify: true,
      highlight(code, language) {
        const validLang = !!(language && HighlightJS.getLanguage(language));
        if (validLang) {
          const lang = language != null ? language : "";
          return highlightBlock(HighlightJS.highlight(code, { language: lang }).value, lang);
        }
        return highlightBlock(HighlightJS.highlightAuto(code).value, "");
      }
    });
    mdi.use(markdownItLinkAttributes, { attrs: { target: "_blank", rel: "noopener" } });
    const text = computed(() => {
      var _a;
      const value = (_a = props.text) != null ? _a : "";
      if (!props.asRawText) {
        return mdi.render(value);
      }
      return value;
    });
    function highlightBlock(str, lang) {
      return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">\u590D\u5236\u4EE3\u7801</span></div><code class="hljs code-block-body ${lang}">${str}</code></pre>`;
    }
    function addCopyEvents() {
      if (textRef.value) {
        const copyBtn = textRef.value.querySelectorAll(".code-block-header__copy");
        copyBtn.forEach((btn) => {
          btn.addEventListener("click", () => {
            var _a, _b;
            const code = (_b = (_a = btn.parentElement) == null ? void 0 : _a.nextElementSibling) == null ? void 0 : _b.textContent;
            if (code) {
              copyToClipboard(code);
              btn.textContent = "\u590D\u5236\u6210\u529F";
              setTimeout(() => {
                btn.textContent = "\u590D\u5236\u4EE3\u7801";
              }, 1e3);
            }
          });
        });
      }
    }
    function removeCopyEvents() {
      if (textRef.value) {
        const copyBtn = textRef.value.querySelectorAll(".code-block-header__copy");
        copyBtn.forEach((btn) => {
          btn.removeEventListener("click", () => {
          });
        });
      }
    }
    onMounted(() => {
      addCopyEvents();
    });
    onUpdated(() => {
      addCopyEvents();
    });
    onUnmounted(() => {
      removeCopyEvents();
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass(["chatai-text-wrapper", props.inversion ? "chatai-text-ask" : "chatai-text-replay", props.error ? "red" : ""])
      }, [
        createElementVNode("div", {
          ref_key: "textRef",
          ref: textRef,
          class: "chatai-text-box"
        }, [
          !props.inversion ? (openBlock(), createElementBlock("div", _hoisted_1$4, [
            !props.asRawText ? (openBlock(), createElementBlock("div", {
              key: 0,
              class: "markdown-body",
              innerHTML: text.value
            }, null, 8, _hoisted_2$4)) : (openBlock(), createElementBlock("div", {
              key: 1,
              class: "chatai-pre-wrap",
              textContent: toDisplayString(text.value)
            }, null, 8, _hoisted_3$4))
          ])) : (openBlock(), createElementBlock("div", {
            key: 1,
            class: "chatai-pre-wrap",
            textContent: toDisplayString(text.value)
          }, null, 8, _hoisted_4$3)),
          props.loading ? (openBlock(), createElementBlock("span", _hoisted_5$3)) : createCommentVNode("", true)
        ], 512)
      ], 2);
    };
  }
};
var defaultAvatar = "";
var defaultChat = "";
const _sfc_main$5 = {
  __name: "avatar",
  props: {
    userImg: {
      type: String,
      default: ""
    },
    chatImg: {
      type: String,
      default: ""
    },
    inversion: {
      type: Boolean
    }
  },
  setup(__props) {
    const props = __props;
    return (_ctx, _cache) => {
      const _component_a_avatar = Avatar;
      return props.inversion ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
        props.userImg ? (openBlock(), createBlock(_component_a_avatar, {
          key: 0,
          src: props.userImg
        }, null, 8, ["src"])) : (openBlock(), createBlock(_component_a_avatar, {
          key: 1,
          src: unref(defaultAvatar)
        }, null, 8, ["src"]))
      ], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
        props.chatImg ? (openBlock(), createBlock(_component_a_avatar, {
          key: 0,
          src: props.chatImg
        }, null, 8, ["src"])) : (openBlock(), createBlock(_component_a_avatar, {
          key: 1,
          src: unref(defaultChat)
        }, null, 8, ["src"]))
      ], 64));
    };
  }
};
var index_vue_vue_type_style_index_0_lang$2 = "";
const _hoisted_1$3 = { class: "chatai-avatar-box" };
const _hoisted_2$3 = { class: "chatai-content-box" };
const _hoisted_3$3 = { class: "chatai-date" };
const _hoisted_4$2 = { class: "chatai-msg-box" };
const _hoisted_5$2 = ["data-index"];
const _hoisted_6$1 = { class: "chatai-opeate" };
const _hoisted_7$1 = {
  key: 0,
  class: "chatai-source-box"
};
const _hoisted_8$1 = { class: "chatai-source-links" };
const _hoisted_9$1 = ["onClick"];
const _sfc_main$4 = {
  __name: "index",
  props: {
    inversion: {
      type: Boolean,
      default: false
    },
    text: {
      type: String,
      default: ""
    },
    dateTime: {
      type: String,
      default: ""
    },
    error: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => ({})
    },
    feature: {
      type: Object,
      default: () => ({})
    },
    chatImg: {
      type: String,
      default: ""
    },
    userImg: {
      type: String,
      default: ""
    },
    index: {
      type: Number,
      default: 0
    }
  },
  emits: ["regenerate", "delete", "openFilePreview"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const isMobile = useMobile();
    const popoverVisible = ref(false);
    const messageRef = ref(null);
    function handleRegenerate() {
      emits("regenerate", { messageRef });
    }
    function handleCopy() {
      popoverVisible.value = false;
      try {
        copyToClipboard(props.text || "");
        message.success("\u590D\u5236\u6210\u529F");
      } catch {
        message.error("\u590D\u5236\u5931\u8D25");
      }
    }
    function handleDelete() {
      popoverVisible.value = false;
      emits("delete");
    }
    return (_ctx, _cache) => {
      const _component_icon_svg = IconSvg;
      const _component_a_tooltip = __unplugin_components_1$1;
      const _component_a_popover = __unplugin_components_2$1;
      return openBlock(), createElementBlock("div", {
        ref_key: "messageRef",
        ref: messageRef,
        class: normalizeClass(["chatai-msg-wapper", __props.inversion ? "reverse" : ""])
      }, [
        createElementVNode("div", _hoisted_1$3, [
          createVNode(_sfc_main$5, {
            inversion: __props.inversion,
            chatImg: props.chatImg,
            userImg: props.userImg
          }, null, 8, ["inversion", "chatImg", "userImg"])
        ]),
        createElementVNode("div", _hoisted_2$3, [
          createElementVNode("div", _hoisted_3$3, toDisplayString(__props.dateTime), 1),
          createElementVNode("div", _hoisted_4$2, [
            createElementVNode("div", {
              class: "chatai-replay-box",
              "data-index": props.index
            }, [
              createVNode(_sfc_main$6, {
                inversion: __props.inversion,
                error: __props.error,
                text: __props.text,
                loading: __props.loading,
                "as-raw-text": __props.inversion
              }, null, 8, ["inversion", "error", "text", "loading", "as-raw-text"])
            ], 8, _hoisted_5$2),
            createElementVNode("div", _hoisted_6$1, [
              props.feature.retryReply ? (openBlock(), createBlock(_component_a_tooltip, {
                key: 0,
                placement: "top",
                trigger: "hover",
                title: unref(isMobile) ? false : "\u91CD\u65B0\u83B7\u53D6",
                getPopupContainer: unref(getPopupContainer)
              }, {
                default: withCtx(() => [
                  !__props.inversion ? (openBlock(), createBlock(_component_icon_svg, {
                    key: 0,
                    type: "refresh",
                    size: "14",
                    onClick: handleRegenerate
                  })) : createCommentVNode("", true)
                ]),
                _: 1
              }, 8, ["title", "getPopupContainer"])) : createCommentVNode("", true),
              props.feature.copyChat || props.feature.delChat ? (openBlock(), createBlock(_component_a_popover, {
                key: 1,
                trigger: "hover",
                placement: !__props.inversion ? "right" : "left",
                overlayClassName: "chatai-msg-opeate",
                visible: popoverVisible.value,
                "onUpdate:visible": _cache[0] || (_cache[0] = ($event) => popoverVisible.value = $event),
                getPopupContainer: unref(getPopupContainer)
              }, {
                content: withCtx(() => [
                  props.feature.copyChat ? (openBlock(), createElementBlock("div", {
                    key: 0,
                    onClick: handleCopy,
                    class: "chatai-tool"
                  }, [
                    createVNode(_component_icon_svg, { type: "copy" }),
                    createTextVNode("\xA0\u590D\u5236")
                  ])) : createCommentVNode("", true),
                  props.feature.delChat ? (openBlock(), createElementBlock("div", {
                    key: 1,
                    onClick: handleDelete,
                    class: "chatai-tool"
                  }, [
                    createVNode(_component_icon_svg, { type: "delete" }),
                    createTextVNode("\xA0\u5220\u9664")
                  ])) : createCommentVNode("", true)
                ]),
                default: withCtx(() => [
                  createVNode(_component_icon_svg, {
                    type: "more",
                    size: "14"
                  })
                ]),
                _: 1
              }, 8, ["placement", "visible", "getPopupContainer"])) : createCommentVNode("", true)
            ])
          ]),
          props.feature.source ? renderSlot(_ctx.$slots, "source", normalizeProps(mergeProps({ key: 0 }, props.data)), () => [
            props.data.source && !props.loading && !props.inversion ? (openBlock(), createElementBlock("div", _hoisted_7$1, [
              createVNode(_component_icon_svg, {
                type: "file",
                viewBox: "0 0 1024 1024",
                width: "20",
                height: "20"
              }),
              createElementVNode("div", _hoisted_8$1, [
                (openBlock(true), createElementBlock(Fragment, null, renderList(props.data.source, (item, index) => {
                  return openBlock(), createBlock(_component_a_tooltip, {
                    title: item.tooltip || false,
                    key: index,
                    getPopupContainer: unref(getPopupContainer)
                  }, {
                    default: withCtx(() => [
                      createElementVNode("span", {
                        class: "chatai-source-link",
                        onClick: ($event) => _ctx.$emit("openFilePreview", item)
                      }, toDisplayString(item.showName || item.fileName), 9, _hoisted_9$1)
                    ]),
                    _: 2
                  }, 1032, ["title", "getPopupContainer"]);
                }), 128))
              ])
            ])) : createCommentVNode("", true)
          ]) : createCommentVNode("", true)
        ])
      ], 2);
    };
  }
};
function useScroll() {
  const scrollRef = ref(null);
  const scrollToBottom = async () => {
    await nextTick();
    if (scrollRef.value) {
      scrollRef.value.scrollTop = scrollRef.value.scrollHeight;
    }
  };
  const scrollToTop = async () => {
    await nextTick();
    if (scrollRef.value) {
      scrollRef.value.scrollTop = 0;
    }
  };
  const scrollToBottomIfAtBottom = async () => {
    await nextTick();
    if (scrollRef.value) {
      const threshold = 100;
      const distanceToBottom = scrollRef.value.scrollHeight - scrollRef.value.scrollTop - scrollRef.value.clientHeight;
      if (distanceToBottom <= threshold)
        scrollRef.value.scrollTop = scrollRef.value.scrollHeight;
    }
  };
  return {
    scrollRef,
    scrollToBottom,
    scrollToTop,
    scrollToBottomIfAtBottom
  };
}
let initConfig = {
  defaultUUid: 10,
  feature: {
    chatSaveToStorage: true,
    isUsingContext: true,
    clearChat: true,
    exportImage: true,
    delChat: true,
    copyChat: true,
    retryReply: true,
    stopReply: true,
    source: true
  },
  storage: {
    key: "CHATAISTATE",
    expire: null,
    maxCount: 50
  },
  exportImageWatermark: {
    text: "\u529B\u77F3\u79D1\u6280",
    font: "14px microsoft yahei",
    color: "rgba(238, 36, 5, 0.1)",
    spaceX: 160,
    spaceY: 120,
    angle: -25 * Math.PI / 180
  }
};
let config = { ...initConfig };
var index_vue_vue_type_style_index_0_lang$1 = "";
const _hoisted_1$2 = /* @__PURE__ */ createElementVNode("div", { class: "chatai-pdf-seat" }, null, -1);
const _hoisted_2$2 = { class: "chatai-pdf-wrapper" };
const _hoisted_3$2 = /* @__PURE__ */ createElementVNode("div", { class: "chatai-pdf-seat" }, null, -1);
const SANDBOX_BUNDLE_SRC = "https://cdnv2.lishicloud.com/biz/bl/xz/js/pdf/pdf.sandbox.js";
const CMAP_URL = "https://cdn.jsdelivr.net/npm/pdfjs-dist@3.8.162/cmaps/";
const _sfc_main$3 = {
  __name: "index",
  props: {
    url: {
      type: String,
      required: true,
      default: ""
    },
    page: {
      type: Number,
      default: 1
    },
    keyword: {
      type: String,
      default: ""
    },
    isJudgeBeforeFind: {
      type: Boolean,
      default: false
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: ["pagesloaded", "progress", "pagesinit", "close"],
  setup(__props, { expose: __expose, emit: __emit }) {
    pdf.exports.GlobalWorkerOptions.workerSrc = "https://cdnv2.lishicloud.com/biz/bl/xz/js/pdf/pdf.worker.js";
    const props = __props;
    const emits = __emit;
    const pageContainer = ref();
    const loading = ref(false);
    const eventBus = new pdf_viewer.exports.EventBus();
    let pdfViewer = null;
    let pdfDocument = null;
    let hasInit = false;
    const pdfLinkService = new pdf_viewer.exports.PDFLinkService({
      eventBus
    });
    const pdfFindController = new pdf_viewer.exports.PDFFindController({
      eventBus,
      linkService: pdfLinkService
    });
    const pdfScriptingManager = new pdf_viewer.exports.PDFScriptingManager({
      eventBus,
      sandboxBundleSrc: SANDBOX_BUNDLE_SRC
    });
    watch(() => [props.visible, props.url, props.page, props.keyword], ([visible, url, page, keyword], [preVisible, preUrl]) => {
      if (!visible)
        return;
      if (preUrl !== url) {
        load(url);
      } else {
        page && (pdfViewer.currentPageNumber = page);
        if (keyword) {
          eventBus.dispatch("find", { type: "", query: keyword });
        }
      }
    });
    onUnmounted(() => {
      pdfViewer == null ? void 0 : pdfViewer.cleanup();
      pdfDocument == null ? void 0 : pdfDocument.destroy();
    });
    async function load(url) {
      if (hasInit) {
        loadPdf(url);
        return;
      }
      hasInit = true;
      pdfViewer = new pdf_viewer.exports.PDFViewer({
        container: pageContainer.value,
        eventBus,
        linkService: pdfLinkService,
        findController: pdfFindController,
        scriptingManager: pdfScriptingManager
      });
      pdfLinkService.setViewer(pdfViewer);
      pdfScriptingManager.setViewer(pdfViewer);
      eventBus.on("pagesloaded", (evt) => {
        loading.value = false;
        emits("pagesloaded", { pdfDocument, pdfViewer, evt, eventBus });
      });
      eventBus.on("pagechanging", (evt) => {
        console.log("pagechanging", pdfViewer.currentPageNumber);
      });
      eventBus.on("pagesinit", () => {
        pdfViewer.currentPageNumber = props.page;
        pdfViewer.currentScaleValue = "page-width";
        emits("pagesinit", { pdfDocument, pdfViewer, eventBus });
        if (props.keyword) {
          if (props.isJudgeBeforeFind) {
            isTextInPage(props.keyword, props.page).then((res) => {
              if (!res)
                return;
              eventBus.dispatch("find", { type: "", query: props.keyword });
            });
          } else {
            eventBus.dispatch("find", { type: "", query: props.keyword });
          }
        }
      });
      loadPdf(url);
    }
    async function loadPdf(url) {
      if (!url)
        return;
      loading.value = true;
      const loadingTask = pdf.exports.getDocument({
        url,
        cMapUrl: CMAP_URL,
        cMapPacked: true,
        enableXfa: true
      });
      loadingTask.onProgress = ({
        loaded,
        total
      }) => {
        const percentage = loaded / total;
        emits("progress", percentage);
        if (percentage === 1) {
          loading.value = false;
        }
      };
      pdfDocument = await loadingTask.promise;
      pdfViewer.setDocument(pdfDocument);
      pdfLinkService.setDocument(pdfDocument, null);
    }
    async function findAtPage(searchText, pageNumber) {
      try {
        const page = await pdfDocument.getPage(pageNumber);
        const textContent = await page.getTextContent({
          disableNormalization: true
        });
        const strBuf = [];
        for (const textItem of textContent.items) {
          strBuf.push(textItem.str);
          if (textItem.hasEOL) {
            strBuf.push("\n");
          }
        }
        const allText = strBuf.join("");
        console.log("allText:", allText);
        const reg = new RegExp("(.{0,20})" + searchText + "(.{0,20})", "gi");
        let m;
        let lines = [];
        while (m = reg.exec(allText)) {
          let line = (m[1] ? "..." : "") + m[0] + (m[2] ? "..." : "");
          lines.push(line);
        }
        return { page: pageNumber, items: lines };
      } catch (err) {
        return { items: [] };
      }
    }
    async function isTextInPage(text, pageNumber) {
      const result = await findAtPage(text, pageNumber);
      return result.items.length > 0 ? true : false;
    }
    __expose({ pdfDocument, eventBus, pdfViewer });
    return (_ctx, _cache) => {
      const _component_a_drawer = __unplugin_components_0;
      return openBlock(), createBlock(_component_a_drawer, mergeProps({
        class: "chatai-pdf-drawer",
        placement: "left",
        forceRender: true,
        visible: props.visible || false,
        width: 800,
        onClose: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("close")),
        closable: false
      }, _ctx.$attrs), {
        default: withCtx(() => [
          _hoisted_1$2,
          createElementVNode("div", _hoisted_2$2, [
            createElementVNode("div", {
              ref_key: "pageContainer",
              ref: pageContainer,
              class: "chatai-pdf-containner"
            }, [
              createElementVNode("div", {
                class: "pdfViewer",
                style: normalizeStyle({ display: loading.value ? "none" : "block" })
              }, null, 4),
              loading.value ? renderSlot(_ctx.$slots, "default", { key: 0 }) : createCommentVNode("", true)
            ], 512)
          ]),
          _hoisted_3$2
        ]),
        _: 3
      }, 16, ["visible"]);
    };
  }
};
var index_vue_vue_type_style_index_0_lang = "";
const _hoisted_1$1 = { class: "chatai-confirm" };
const _hoisted_2$1 = { class: "title-box" };
const _hoisted_3$1 = { class: "title" };
const _hoisted_4$1 = { class: "content" };
const _hoisted_5$1 = { class: "footer" };
const _sfc_main$2 = {
  __name: "index",
  props: {
    data: {
      type: Object,
      default: () => ({})
    }
  },
  setup(__props) {
    let initValue = {
      title: "",
      content: "",
      closable: false,
      okText: "\u786E\u5B9A",
      cancelText: "\u53D6\u6D88",
      onOk: () => {
      },
      onCancel: () => {
      }
    };
    const props = __props;
    const curData = computed(() => {
      return { ...initValue, ...props.data };
    });
    return (_ctx, _cache) => {
      const _component_a_button = Button;
      const _component_a_modal = Modal;
      return openBlock(), createBlock(_component_a_modal, {
        visible: curData.value.visible,
        "onUpdate:visible": _cache[0] || (_cache[0] = ($event) => curData.value.visible = $event),
        footer: null,
        closable: curData.value.closable,
        width: 420,
        centered: true
      }, {
        default: withCtx(() => [
          createElementVNode("div", _hoisted_1$1, [
            createElementVNode("div", _hoisted_2$1, [
              createVNode(unref(ExclamationCircleOutlined)),
              createElementVNode("span", _hoisted_3$1, toDisplayString(curData.value.title), 1)
            ]),
            createElementVNode("div", _hoisted_4$1, toDisplayString(curData.value.content), 1),
            createElementVNode("div", _hoisted_5$1, [
              createVNode(_component_a_button, {
                onClick: curData.value.onCancel
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(curData.value.cancelText), 1)
                ]),
                _: 1
              }, 8, ["onClick"]),
              createVNode(_component_a_button, {
                type: "primary",
                onClick: curData.value.onOk
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(curData.value.okText), 1)
                ]),
                _: 1
              }, 8, ["onClick"])
            ])
          ])
        ]),
        _: 1
      }, 8, ["visible", "closable"]);
    };
  }
};
function fetchChatProcess({
  data = { prompt: "" },
  signal,
  onDownloadProgress,
  extraParams = () => ({})
}) {
  const params = typeof extraParams.request === "function" ? extraParams.request({
    signal,
    data,
    onDownloadProgress,
    request: fetchEventSource,
    useScroll,
    chatStore: extraParams.chatStore
  }) : extraParams.request || {};
  if (params === false)
    return;
  const { url, headers = {}, ...rest } = params;
  return fetchEventSource(url, {
    method: "POST",
    signal,
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json",
      ...headers
    },
    onmessage: (evt) => {
      if (extraParams.transformResponse) {
        const result = extraParams.transformResponse(evt);
        onDownloadProgress == null ? void 0 : onDownloadProgress(result);
        return;
      }
      try {
        const result = JSON.parse(evt.data);
        onDownloadProgress == null ? void 0 : onDownloadProgress(result);
      } catch (error) {
        try {
          const temp = JSON.parse(evt.decodeValue);
          if (temp.message) {
            const result = { text: temp.message };
            onDownloadProgress == null ? void 0 : onDownloadProgress(result);
          }
        } catch (err) {
          console.log("fetch msg parse error: ", error);
        }
      }
    },
    onerror(err) {
      console.log("fetch msg error:", err);
    },
    ...rest
  });
}
var main_vue_vue_type_style_index_0_lang = "";
const _hoisted_1 = { class: "chatai-wrapper" };
const _hoisted_2 = { class: "chatai-content-wrapper" };
const _hoisted_3 = { class: "chatai-main-wrapper" };
const _hoisted_4 = { class: "chatai-hello-msg" };
const _hoisted_5 = /* @__PURE__ */ createElementVNode("span", { style: { "margin-left": "10px" } }, "\u4F60\u597D~", -1);
const _hoisted_6 = {
  key: 1,
  class: "chatai-msg-list"
};
const _hoisted_7 = {
  key: 0,
  class: "chatai-stop-response"
};
const _hoisted_8 = /* @__PURE__ */ createElementVNode("span", null, "\xA0\u505C\u6B62\u54CD\u5E94", -1);
const _hoisted_9 = { class: "chatai-footer-wrapper" };
const _hoisted_10 = { class: "chatai-footer-content" };
const _hoisted_11 = { class: "chatai-msg-input" };
const _hoisted_12 = { class: "chatai-preview-loading" };
const _sfc_main$1 = {
  __name: "main",
  props: {
    placeholder: {
      type: [String, Function],
      default: ""
    },
    requestOptions: {
      type: [Function, Object],
      default: () => ({})
    },
    formatData: {
      type: Function,
      default: (data) => ({ text: data.text, replayOptions: {}, source: data.source })
    },
    transformResponse: {
      type: Function,
      default: null
    },
    chatImg: {
      type: String,
      default: ""
    },
    userImg: {
      type: String,
      default: ""
    },
    inputProps: {
      type: Object,
      default: () => ({})
    },
    feature: {
      type: Object,
      default: () => ({})
    },
    route: {
      type: Object,
      default: null
    },
    chatStore: {
      type: Object,
      default: () => ({})
    },
    filterWords: {
      type: Function,
      default: async ({ promptRef, prompt }) => true
    },
    exportImageWatermark: {
      type: Object,
      default: () => ({})
    },
    fileLinkClassName: {
      type: String,
      default: "js-file-link"
    }
  },
  setup(__props) {
    var _a, _b, _c, _d;
    const fetchChatProcess$1 = fetchChatProcess;
    const isMobile = useMobile();
    const props = __props;
    const placeholder = computed(() => {
      if (props.placeholder) {
        return typeof props.placeholder === "function" ? props.placeholder(isMobile) : props.placeholder;
      } else {
        return isMobile.value ? "\u8BF4\u70B9\u4EC0\u4E48\u5427" : "\u6765\u8BF4\u70B9\u4EC0\u4E48\u5427...\uFF08Shift + Enter = \u6362\u884C\uFF09";
      }
    });
    const curFile = ref({});
    const filePreivewVisible = ref(null);
    function closeFilePreview() {
      filePreivewVisible.value = false;
    }
    function openFilePreview(item) {
      const temp = item.fileUrl.split(".");
      if (temp.slice(-1)[0] !== "pdf") {
        window.open(item.fileUrl);
        return;
      }
      curFile.value = item;
      filePreivewVisible.value = true;
    }
    function getParentElByClass(curDom, parentClass) {
      let parent = null;
      while (parent = curDom == null ? void 0 : curDom.parentNode) {
        if (parent.classList.contains(parentClass)) {
          return parent;
        } else {
          curDom = parent;
        }
      }
      return null;
    }
    function bindLinkFileClick(evt) {
      var _a2;
      const { target } = evt;
      if (target.classList.contains(props.fileLinkClassName)) {
        const { id } = target.dataset;
        const pEl = getParentElByClass(target, "chatai-replay-box");
        const index = pEl ? pEl.dataset.index : -1;
        if (index > -1) {
          const source = ((_a2 = dataSources.value[index]) == null ? void 0 : _a2.source) || [];
          const item = source.find((v) => parseInt(v.id) === parseInt(id));
          item && openFilePreview(item);
        }
      }
    }
    onMounted(() => {
      scrollBox.value.addEventListener("click", bindLinkFileClick);
    });
    onUnmounted(() => {
      var _a2;
      (_a2 = scrollBox.value) == null ? void 0 : _a2.removeEventListener("click", bindLinkFileClick);
    });
    const {
      scrollRef,
      scrollToBottom,
      scrollToBottomIfAtBottom
    } = useScroll();
    const {
      addChat,
      updateIndexChat,
      updateIndexChatSome,
      getChat,
      getIndexChat,
      delIndexChat,
      clearChat,
      chatStateRef
    } = props.chatStore;
    const uuid = ref(parseInt((_d = (_c = (_b = (_a = props.route) == null ? void 0 : _a.params) == null ? void 0 : _b.uuid) != null ? _c : chatStateRef.value.active) != null ? _d : config.defaultUUid));
    if (props.route) {
      watch(() => props.route.params.uuid, (newValue) => {
        if (parseInt(newValue) !== uuid.value) {
          destoryPage();
          setTimeout(() => {
            uuid.value = parseInt(newValue || config.defaultUUid);
            initPage();
          });
        }
      });
    } else {
      watch(() => chatStateRef.value.active, (newValue) => {
        destoryPage();
        setTimeout(() => {
          uuid.value = parseInt(newValue || config.defaultUUid);
          initPage();
        });
      });
    }
    const dataSources = computed(() => getChat(uuid.value));
    const replayList = computed(() => dataSources.value.filter((item) => !item.inversion && !!item.replayOptions));
    const confirmModalData = ref({});
    const scrollBox = ref(null);
    const inputRef = ref(null);
    const loading = ref(false);
    const prompt = ref("");
    const exportBtnDisabled = ref(false);
    const sendBtnDisabled = computed(() => {
      return loading.value || prompt.value.trim().length === 0;
    });
    let controller = new AbortController();
    const onRegenerate = async (index, { messageRef }) => {
      if (loading.value) {
        message.warn("\u6B63\u5728\u52A0\u8F7D\uFF0C\u6682\u65F6\u65E0\u6CD5\u91CD\u65B0\u83B7\u53D6");
        return;
      }
      messageRef.value.scrollIntoView();
      controller = new AbortController();
      const { requestOptions } = dataSources.value[index];
      loading.value = true;
      updateIndexChat(
        uuid.value,
        index,
        {
          dateTime: new Date().toLocaleString(),
          text: "",
          inversion: false,
          error: false,
          loading: true,
          replayOptions: null,
          requestOptions
        }
      );
      try {
        await fetchChatProcess$1({
          data: simpleDeepClone(requestOptions),
          signal: controller.signal,
          extraParams: {
            request: props.requestOptions,
            chatStore: props.chatStore,
            transformResponse: props.transformResponse
          },
          onDownloadProgress(data) {
            const { text, replayOptions = {}, source, ...rest } = props.formatData(data);
            updateIndexChat(
              uuid.value,
              index,
              {
                dateTime: new Date().toLocaleString(),
                text: text != null ? text : "",
                inversion: false,
                error: false,
                loading: true,
                replayOptions,
                requestOptions,
                source,
                ...rest
              }
            );
            scrollToBottomIfAtBottom();
          }
        });
        updateIndexChatSome(uuid.value, index, { loading: false });
      } catch (error) {
        handleChatError({
          error,
          index,
          requestOptions
        });
      } finally {
        loading.value = false;
      }
    };
    const handleEnter = (event) => {
      if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault();
        handleSubmit();
      }
    };
    const handleSubmit = async () => {
      var _a2;
      if (sendBtnDisabled.value)
        return;
      if (props.filterWords) {
        const res = await props.filterWords({
          prompt: prompt.value,
          promptRef: prompt
        });
        if (res === false)
          return;
      }
      const message2 = prompt.value;
      controller = new AbortController();
      addChat(
        uuid.value,
        {
          dateTime: new Date().toLocaleString(),
          text: message2,
          inversion: true,
          error: false,
          replayOptions: null,
          requestOptions: { prompt: message2, options: null }
        }
      );
      scrollToBottom();
      loading.value = true;
      prompt.value = "";
      let options = {};
      const lastContext = (_a2 = replayList.value[replayList.value.length - 1]) == null ? void 0 : _a2.replayOptions;
      if (lastContext && props.feature.isUsingContext) {
        options = { ...lastContext };
      }
      const requestOptions = { prompt: message2, options };
      addChat(
        uuid.value,
        {
          dateTime: new Date().toLocaleString(),
          text: "",
          loading: true,
          inversion: false,
          error: false,
          replayOptions: null,
          requestOptions
        }
      );
      scrollToBottom();
      try {
        const curIndex = dataSources.value.length - 1;
        await fetchChatProcess$1({
          data: simpleDeepClone(requestOptions),
          signal: controller.signal,
          extraParams: {
            request: props.requestOptions,
            chatStore: props.chatStore,
            transformResponse: props.transformResponse
          },
          onDownloadProgress(data) {
            const { text, replayOptions = {}, source, ...rest } = props.formatData(data);
            updateIndexChat(
              uuid.value,
              curIndex,
              {
                dateTime: new Date().toLocaleString(),
                text: text != null ? text : "",
                inversion: false,
                error: false,
                loading: true,
                replayOptions,
                requestOptions,
                source,
                ...rest
              }
            );
            scrollToBottomIfAtBottom();
          }
        });
        updateIndexChatSome(uuid.value, curIndex, { loading: false });
      } catch (error) {
        handleChatError({
          error,
          index: dataSources.value.length - 1,
          requestOptions,
          isScroll: true
        });
      } finally {
        loading.value = false;
      }
    };
    function handleChatError({ error, index, requestOptions, isScroll = false } = {}) {
      if (error.message === "canceled") {
        updateIndexChatSome(
          uuid.value,
          index,
          {
            loading: false
          }
        );
        isScroll && scrollToBottomIfAtBottom();
        return;
      }
      console.log("chat replay error: ", error);
      let errorMessage = getErrorMsg(error == null ? void 0 : error.message);
      const currentChat = getIndexChat(uuid.value, index);
      if ((currentChat == null ? void 0 : currentChat.text) && currentChat.text !== "") {
        updateIndexChatSome(
          uuid.value,
          index,
          {
            text: `${currentChat.text}
[${errorMessage}]`,
            error: false,
            loading: false
          }
        );
        return;
      }
      updateIndexChat(
        uuid.value,
        index,
        {
          dateTime: new Date().toLocaleString(),
          text: errorMessage,
          inversion: false,
          error: true,
          loading: false,
          replayOptions: null,
          requestOptions
        }
      );
      isScroll && scrollToBottomIfAtBottom();
    }
    function getErrorMsg(errorMsg) {
      errorMsg = errorMsg != null ? errorMsg : "\u597D\u50CF\u51FA\u9519\u4E86\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5";
      if (errorMsg.includes("The user aborted a request")) {
        errorMsg = "\u7528\u6237\u4E2D\u6B62\u4E86\u8BF7\u6C42";
      }
      return errorMsg;
    }
    const handleStop = () => {
      if (loading.value) {
        controller.abort();
        loading.value = false;
      }
    };
    const handleDelete = (index) => {
      if (loading.value) {
        message.warn("\u6B63\u5728\u52A0\u8F7D\uFF0C\u6682\u65F6\u4E0D\u80FD\u5220\u9664\u6D88\u606F");
        return;
      }
      confirmModalData.value = {
        visible: true,
        title: "\u5220\u9664\u6D88\u606F",
        content: "\u662F\u5426\u5220\u9664\u6B64\u6D88\u606F?",
        onOk() {
          delIndexChat(uuid.value, index);
          confirmModalData.value.visible = false;
        },
        onCancel() {
          confirmModalData.value.visible = false;
        }
      };
    };
    const handleClear = () => {
      if (loading.value) {
        message.warn("\u6B63\u5728\u52A0\u8F7D\uFF0C\u6682\u65F6\u4E0D\u80FD\u6E05\u7A7A\u6D88\u606F");
        return;
      }
      confirmModalData.value = {
        visible: true,
        title: "\u6E05\u7A7A\u6D88\u606F",
        content: "\u662F\u5426\u6E05\u7A7A\u5F53\u524D\u6D88\u606F?",
        onOk() {
          clearChat(uuid.value);
          confirmModalData.value.visible = false;
        },
        onCancel() {
          confirmModalData.value.visible = false;
        }
      };
    };
    const handleExport = async () => {
      if (loading.value || exportBtnDisabled.value || !scrollBox.value) {
        message.warn("\u6B63\u5728\u52A0\u8F7D\u6216\u4E0B\u8F7D\u56FE\u7247\uFF0C\u6682\u65F6\u4E0D\u80FD\u4FDD\u5B58\u56FE\u7247");
        return;
      }
      exportBtnDisabled.value = true;
      try {
        await exportToImage(scrollBox.value, props.exportImageWatermark);
        message.success("\u5BFC\u51FA\u6210\u529F");
      } catch (err) {
        message.error("\u5BFC\u51FA\u5931\u8D25");
      } finally {
        exportBtnDisabled.value = false;
      }
    };
    function initPage() {
      var _a2;
      scrollToBottom();
      if (inputRef.value) {
        (_a2 = inputRef.value) == null ? void 0 : _a2.focus();
      }
    }
    function destoryPage() {
      if (loading.value) {
        controller.abort();
      }
    }
    onMounted(initPage);
    onUnmounted(destoryPage);
    onMounted(() => {
      setScrollNode(scrollRef.value);
    });
    return (_ctx, _cache) => {
      const _component_a_button = Button;
      const _component_hover_botton = _sfc_main$7;
      const _component_a_textarea = __unplugin_components_2$2;
      const _component_a_spin = Spin;
      return openBlock(), createElementBlock("div", _hoisted_1, [
        createElementVNode("div", _hoisted_2, [
          createElementVNode("main", _hoisted_3, [
            createElementVNode("div", {
              class: "chatai-scroll-wrapper",
              ref_key: "scrollRef",
              ref: scrollRef
            }, [
              createElementVNode("div", {
                class: "chatai-scroll-box",
                ref_key: "scrollBox",
                ref: scrollBox
              }, [
                !dataSources.value.length ? renderSlot(_ctx.$slots, "empty", { key: 0 }, () => [
                  createElementVNode("div", _hoisted_4, [
                    createVNode(IconSvg, {
                      type: "hello-msg",
                      size: 26
                    }),
                    _hoisted_5
                  ])
                ]) : (openBlock(), createElementBlock("div", _hoisted_6, [
                  (openBlock(true), createElementBlock(Fragment, null, renderList(dataSources.value, (item, index) => {
                    return openBlock(), createBlock(_sfc_main$4, {
                      key: index,
                      index,
                      "date-time": item.dateTime,
                      inversion: item.inversion,
                      text: item.text,
                      error: item.error,
                      loading: item.loading,
                      data: item,
                      onRegenerate: (params) => onRegenerate(index, params),
                      onDelete: ($event) => handleDelete(index),
                      feature: props.feature,
                      chatImg: props.chatImg,
                      userImg: props.userImg,
                      onOpenFilePreview: openFilePreview
                    }, {
                      source: withCtx((data) => [
                        renderSlot(_ctx.$slots, "source", normalizeProps(guardReactiveProps(data)))
                      ]),
                      _: 2
                    }, 1032, ["index", "date-time", "inversion", "text", "error", "loading", "data", "onRegenerate", "onDelete", "feature", "chatImg", "userImg"]);
                  }), 128)),
                  props.feature.stopReply ? (openBlock(), createElementBlock("div", _hoisted_7, [
                    loading.value ? (openBlock(), createBlock(_component_a_button, {
                      key: 0,
                      danger: "",
                      onClick: handleStop
                    }, {
                      icon: withCtx(() => [
                        createVNode(IconSvg, {
                          type: "stop-response",
                          size: "18"
                        })
                      ]),
                      default: withCtx(() => [
                        _hoisted_8
                      ]),
                      _: 1
                    })) : createCommentVNode("", true)
                  ])) : createCommentVNode("", true)
                ]))
              ], 512)
            ], 512)
          ]),
          createElementVNode("footer", _hoisted_9, [
            createElementVNode("div", _hoisted_10, [
              props.feature.clearChat ? (openBlock(), createBlock(_component_hover_botton, {
                key: 0,
                onClick: handleClear,
                tooltip: "\u6E05\u7A7A\u6D88\u606F"
              }, {
                default: withCtx(() => [
                  createVNode(IconSvg, {
                    type: "delete",
                    size: "20"
                  })
                ]),
                _: 1
              })) : createCommentVNode("", true),
              props.feature.exportImage ? (openBlock(), createBlock(_component_hover_botton, {
                key: 1,
                style: { "margin-left": "6px" },
                onClick: handleExport,
                tooltip: "\u4FDD\u5B58\u6D88\u606F\u4E3A\u56FE\u7247"
              }, {
                default: withCtx(() => [
                  createVNode(IconSvg, {
                    type: "download",
                    size: "20",
                    color: exportBtnDisabled.value ? "#c1b5b5" : "currentcolor"
                  }, null, 8, ["color"])
                ]),
                _: 1
              })) : createCommentVNode("", true),
              createElementVNode("div", _hoisted_11, [
                createVNode(_component_a_textarea, mergeProps({
                  "auto-size": { minRows: 1, maxRows: 3 },
                  placeholder: placeholder.value,
                  onPressEnter: handleEnter,
                  value: prompt.value,
                  "onUpdate:value": _cache[0] || (_cache[0] = ($event) => prompt.value = $event),
                  ref_key: "inputRef",
                  ref: inputRef
                }, __props.inputProps), null, 16, ["placeholder", "value"])
              ]),
              createElementVNode("div", {
                class: normalizeClass(["chatai-send-btn", sendBtnDisabled.value ? "disabled" : ""]),
                onClick: handleSubmit
              }, [
                createVNode(IconSvg, { type: "send" })
              ], 2)
            ])
          ])
        ]),
        createVNode(_sfc_main$3, {
          visible: filePreivewVisible.value,
          url: curFile.value.fileUrl,
          page: curFile.value.page,
          keyword: curFile.value.keyword,
          onClose: closeFilePreview
        }, {
          default: withCtx(() => [
            createElementVNode("div", _hoisted_12, [
              createVNode(_component_a_spin)
            ])
          ]),
          _: 1
        }, 8, ["visible", "url", "page", "keyword"]),
        createVNode(_sfc_main$2, { data: confirmModalData.value }, null, 8, ["data"])
      ]);
    };
  }
};
function createStorage(name = "localforage", options = { expire: null }) {
  const defaultExpireTime = 60 * 60 * 24 * 7;
  var store = localforage.createInstance({ name });
  const { expire } = Object.assign({ expire: defaultExpireTime }, options);
  function setItem(key, data) {
    try {
      const storageData = {
        data,
        expire: expire !== null ? new Date().getTime() + expire * 1e3 : null
      };
      store.setItem(key, JSON.stringify(storageData));
    } catch (err) {
      console.log("localforage setItem: ", err);
    }
  }
  async function getItem(key) {
    try {
      let storageData = await store.getItem(key);
      storageData = JSON.parse(storageData);
      if (storageData) {
        const { data, expire: expire2 } = storageData;
        if (expire2 === null || expire2 >= Date.now()) {
          return data;
        }
      }
      removeItem(key);
      return null;
    } catch (err) {
      console.log("localforage getItem: ", err);
    }
  }
  async function removeItem(key) {
    try {
      await store.removeItem(key);
    } catch (err) {
      console.log("localforage removeItem: ", err);
    }
  }
  async function clear() {
    try {
      await store.clear();
    } catch (err) {
      console.log("localforage clear: ", err);
    }
  }
  return { setItem, getItem, removeItem, clear };
}
function getDefaultState(curUuid) {
  const uuid = parseInt(curUuid || config.defaultUUid);
  return {
    active: uuid,
    record: [{ uuid, title: "\u65B0\u7684\u804A\u5929", isEdit: false }],
    chat: [{ uuid, data: [] }]
  };
}
function useChat(params = config) {
  var _a;
  const { feature, storage: storageConfig, router, route } = params;
  const storageKey = "CHATAISTATE";
  const defaultState = getDefaultState((_a = route == null ? void 0 : route.params) == null ? void 0 : _a.uuid);
  const curStorage = createStorage(storageConfig.key, { expire: storageConfig.expire });
  const stateRef = ref(simpleDeepClone(defaultState));
  if (feature.chatSaveToStorage) {
    curStorage.getItem(storageKey).then((value) => {
      stateRef.value = { ...stateRef.value, ...value };
    });
  }
  function getChat(uuid = stateRef.value.active) {
    var _a2, _b;
    return (_b = (_a2 = stateRef.value.chat.find((item) => item.uuid === uuid)) == null ? void 0 : _a2.data) != null ? _b : [];
  }
  function getIndexChat(uuid, index) {
    var _a2, _b;
    const { chat: chatList } = stateRef.value;
    if (!uuid) {
      return (_b = (_a2 = chatList[0]) == null ? void 0 : _a2.data) == null ? void 0 : _b[index];
    }
    return getChat(uuid)[index];
  }
  function addChat(uuid, chat) {
    var _a2;
    const { chat: chatList, record: recordList } = stateRef.value;
    const defaultTitle = defaultState.record[0].title;
    if (!uuid) {
      if (chatList.length) {
        (_a2 = chatList[0].data) == null ? void 0 : _a2.push(chat);
        if (recordList[0].title === defaultTitle) {
          recordList[0].title = chat.text;
        }
        saveState(0, chatList[0].data.length - 1);
      }
      return;
    }
    if (recordList.length === 0) {
      uuid = uuid || Date.now();
      recordList.push({ uuid, title: chat.text, isEdit: false });
      chatList.push({ uuid, data: [chat] });
      stateRef.value.active = uuid;
      saveState();
      return;
    }
    const chatIndex = chatList.findIndex((item) => item.uuid === uuid);
    if (chatIndex !== -1) {
      chatList[chatIndex].data.push(chat);
      if (recordList[chatIndex].title === defaultTitle) {
        recordList[chatIndex].title = chat.text;
      }
      saveState(chatIndex, chatList[chatIndex].data.length - 1);
    }
  }
  function updateIndexChat(uuid, index, chat, some = false) {
    const { chat: chatList } = stateRef.value;
    if (!uuid) {
      if (chatList.length) {
        chatList[0].data[index] = some ? { ...chatList[0].data[index] || {}, ...chat } : chat;
        saveState(0, index);
      }
      return;
    }
    const chatIndex = chatList.findIndex((item) => item.uuid === uuid);
    if (chatIndex !== -1) {
      chatList[chatIndex].data[index] = some ? { ...chatList[chatIndex].data[index] || {}, ...chat } : chat;
      saveState(chatIndex, index);
    }
  }
  function updateIndexChatSome(uuid, index, chat) {
    updateIndexChat(uuid, index, chat, true);
  }
  function delIndexChat(uuid, index) {
    const { chat: chatList } = stateRef.value;
    if (!uuid) {
      if (chatList.length) {
        chatList[0].data.splice(index, 1);
        saveState();
      }
      return;
    }
    const chatIndex = chatList.findIndex((item) => item.uuid === uuid);
    if (chatIndex !== -1) {
      chatList[chatIndex].data.splice(index, 1);
      saveState();
    }
  }
  function clearChat(uuid) {
    const { chat: chatList } = stateRef.value;
    if (!uuid) {
      if (chatList.length) {
        chatList[0].data = [];
        saveState();
      }
      return;
    }
    const chatIndex = chatList.findIndex((item) => item.uuid === uuid);
    if (chatIndex !== -1) {
      chatList[chatIndex].data = [];
      saveState();
    }
  }
  const saveState = debounce((chatIndex = -1, msgIndex = -1) => {
    const stateRefRaw = toRaw(stateRef.value);
    let newState = stateRefRaw;
    if (feature.chatSaveToStorage) {
      if (chatIndex > -1 && msgIndex > -1) {
        const curChat = newState.chat[chatIndex];
        const newChat = {
          uuid: curChat.uuid,
          data: [
            ...curChat.data.slice(0, msgIndex),
            {
              ...curChat.data[msgIndex],
              loading: false
            },
            ...curChat.data.slice(msgIndex + 1)
          ]
        };
        if (storageConfig.maxCount) {
          newChat.data = newChat.data.slice(-storageConfig.maxCount);
        }
        newState = { ...stateRefRaw, chat: [...stateRefRaw.chat] };
        newState.chat[chatIndex] = newChat;
      }
      curStorage.setItem(storageKey, newState);
    }
  }, 30);
  function addRecord(record, chatData = []) {
    const { record: recordList, chat: chatList } = stateRef.value;
    recordList.unshift(record);
    chatList.unshift({ uuid: record.uuid, data: chatData });
    stateRef.value.active = record.uuid;
    reloadRoute(record.uuid);
  }
  function updateRecord(uuid, edit) {
    const { record: recordList } = stateRef.value;
    const index = recordList.findIndex((item) => item.uuid === uuid);
    if (index !== -1) {
      recordList[index] = { ...recordList[index], ...edit };
      saveState();
    }
  }
  function deleteRecord(index) {
    const { record: recordList, chat: chatList } = stateRef.value;
    recordList.splice(index, 1);
    chatList.splice(index, 1);
    if (recordList.length === 0) {
      stateRef.value.active = config.defaultUUid;
      reloadRoute();
      return;
    }
    if (index > 0 && index <= recordList.length) {
      const uuid = recordList[index - 1].uuid;
      stateRef.value.active = uuid;
      reloadRoute(uuid);
      return;
    }
    if (index === 0) {
      if (recordList.length > 0) {
        const uuid = recordList[0].uuid;
        stateRef.value.active = uuid;
        reloadRoute(uuid);
      }
    }
    if (index > recordList.length) {
      const uuid = recordList[recordList.length - 1].uuid;
      stateRef.value.active = uuid;
      reloadRoute(uuid);
    }
  }
  async function setActive(uuid) {
    stateRef.value.active = uuid;
    return await reloadRoute(uuid);
  }
  async function reloadRoute(uuid) {
    saveState();
    if (router) {
      await router.push({ name: route.name, params: { uuid } });
    }
  }
  return {
    addChat,
    updateIndexChat,
    updateIndexChatSome,
    delIndexChat,
    clearChat,
    getChat,
    getIndexChat,
    chatStateRef: stateRef,
    addRecord,
    updateRecord,
    deleteRecord,
    setActive,
    reloadRoute
  };
}
const __default__ = {
  inheritAttrs: false
};
const _sfc_main = Object.assign(__default__, {
  __name: "index",
  props: {
    hasLayout: {
      type: Boolean,
      default: true
    },
    router: {
      type: Object,
      default: null
    },
    route: {
      type: Object,
      default: null
    },
    feature: {
      type: Object,
      default: () => ({})
    },
    storage: {
      type: Object,
      default: () => ({})
    },
    exportImageWatermark: {
      type: Object,
      default: () => ({})
    }
  },
  setup(__props) {
    const props = __props;
    const feature = { ...config.feature, ...props.feature };
    const storage = { ...config.storage, ...props.storage };
    const exportImageWatermark = { ...config.exportImageWatermark, ...props.exportImageWatermark };
    const chatStore = useChat({
      feature,
      storage,
      route: props.route,
      router: props.router
    });
    return (_ctx, _cache) => {
      return props.hasLayout ? (openBlock(), createBlock(_sfc_main$9, {
        key: 0,
        chatStore: unref(chatStore)
      }, {
        default: withCtx(() => [
          createVNode(_sfc_main$1, mergeProps(_ctx.$attrs, {
            chatStore: unref(chatStore),
            feature,
            route: __props.route,
            exportImageWatermark
          }), createSlots({ _: 2 }, [
            renderList(_ctx.$slots, (_, name) => {
              return {
                name,
                fn: withCtx((data) => [
                  renderSlot(_ctx.$slots, name, normalizeProps(guardReactiveProps(data)))
                ])
              };
            })
          ]), 1040, ["chatStore", "route"])
        ]),
        _: 3
      }, 8, ["chatStore"])) : (openBlock(), createBlock(_sfc_main$1, mergeProps({ key: 1 }, _ctx.$attrs, {
        chatStore: unref(chatStore),
        feature,
        route: __props.route,
        exportImageWatermark
      }), createSlots({ _: 2 }, [
        renderList(_ctx.$slots, (_, name) => {
          return {
            name,
            fn: withCtx((data) => [
              renderSlot(_ctx.$slots, name, normalizeProps(guardReactiveProps(data)))
            ])
          };
        })
      ]), 1040, ["chatStore", "route"]));
    };
  }
});
export { _sfc_main as default };
